package org.duanyu.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.val;
import org.apache.dubbo.config.annotation.DubboService;
import org.duanyu.shopping_admin_service.mapper.AdminMapper;
import org.duanyu.shopping_common.pojo.Admin;
import org.duanyu.shopping_common.pojo.Permission;
import org.duanyu.shopping_common.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 管理员模块
 */
@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void AddAdmin(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void UpdateAdmin(Admin admin) {
        //如果前端传来的是空密码，则还使用原来的密码
        if (!StringUtils.hasText(admin.getPassword())){
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }

    @Override
    public void deleteAdmin(Long id) {
        //删除用户的所有角色
        adminMapper.deleteAdminRole(id);
        //删除用户
        adminMapper.deleteById(id);

    }

    @Override
    public Admin findById(Long id) {
        return adminMapper.findById(id);
    }

    @Override
    public Page<Admin> findAllAdmin(int page, int size) {
        return adminMapper.selectPage(new Page<>(page, size), null);
    }

    @Override
    public void updateAdminRole(Long aid, Long[] rid) {
        //删除用户所有角色
        adminMapper.deleteAdminRole(aid);
        //重新添加管理员角色
        for (Long id : rid) {
            adminMapper.addRoleToAdmin(aid, id);
        }
    }

    @Override
    public Admin findByAdminName(String username) {
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("username", username);
        return adminMapper.selectOne(wrapper);
    }

    /**
     * 根据用户名查询所有权限
     * @param username
     * @return
     */
    public List<Permission> findAllPermission(String username) {
        return adminMapper.findAllPermission(username);
    }


}
